<?php
// +----------------------------------------------------------------------
// | llpt system
// +----------------------------------------------------------------------
// | Copyright (c) 2017 llpt All rights reserved.
// +----------------------------------------------------------------------
// | Author: Gooe <zqscjj@163.com> QQ:81009953
// +----------------------------------------------------------------------
namespace app\admin\controller\auth;
use app\common\controller\Admin;
use ddj\Random;
use ddj\Tree;
use think\Validate;
/**
 * 管理员管理
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Adminuser extends Admin
{

    protected $model = null;
    //当前登录管理员所有子节点组别
    protected $childrenIds = [];

    public function initialize()
    {
        parent::initialize();
        $this->model = model('Admin');

        $groups = $this->auth->getGroups();

        // 取出所有分组
        $grouplist = model('AuthGroup')->all(['status' => 1]);
        $objlist = [];
        foreach ($groups as $K => $v)
        {
            // 取出包含自己的所有子节点
            $childrenlist = Tree::instance()->init($grouplist)->getChildren($v['id'], TRUE);
            $obj = Tree::instance()->init($childrenlist)->getTreeArray($v['pid']);
            $objlist = array_merge($objlist, Tree::instance()->getTreeList($obj));
        }
        $groupdata = [];
        foreach ($objlist as $k => $v)
        {
            $groupdata[$v['id']] = $v['name'];
        }
        $this->childrenIds = array_keys($groupdata);
        $this->view->assign('groupdata', $groupdata);
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            $childrenAdminIds = model('AuthGroupAccess')
            ->field('uid')
            ->where('group_id', 'in', $this->childrenIds)
            ->column('uid');
           
            $list = $this->model
            ->where('status','neq',-1)
            ->field('uid,username,nickname,status,login_time')
            ->where('uid', 'in', $childrenAdminIds)
            ->paginate(input('limit',15));
            //返回layui分页
            return json(layui_page($list));
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                //验证
                $validate = new Validate([
                        'username|用户名' => 'require|unique:admin|length:2,30',
                        'nickname|昵称'   => 'require',
                        'password|密码'   => 'require|length:6,30',
                ]);
                $result = $validate->check([
                    'username' => $params['username'],
                    'nickname' => $params['nickname'],
                    'password' => $params['password'],
                ]);
                if (!$result)
                {
                    $this->error($validate->getError());
                }
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);

                $admin = $this->model->create($params);
                $group = $this->request->post("group");
                $group = str2arr($group);
                if (!$group)
                {
                    $this->error('请选择角色组');
                }

                //过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenIds, $group);
                $dataset = [];
                foreach ($group as $value)
                {
                    $dataset[] = ['uid' => $admin->uid, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                $this->success('添加成功');
            }

            return;
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row || $row['status']==-1){
            $this->error('找不到这个用户');
        }
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                
                if ($params['password'])
                {
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                }
                else
                {
                    unset($params['password'], $params['salt']);
                }
                //验证
                $validate = new Validate([
                    'username|用户名' => 'require|length:2,30',
                    'nickname|昵称'   => 'require',
                ]);
                $result = $validate->check([
                    'username' => $params['username'],
                    'nickname' => $params['nickname'],
                ]);
                if (!$result)
                {
                    $this->error($validate->getError());
                }
                $row->allowField(['nickname','password','status','uid','salt'])->save($params);

                // 先移除所有权限
                model('AuthGroupAccess')->where('uid', $row->uid)->delete();

                $group = $this->request->post("group");
                $group = str2arr($group);
                // 过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenIds, $group);
                $dataset = [];
                foreach ($group as $value)
                {
                    $dataset[] = ['uid' => $row->uid, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                $this->success('编辑成功');
            }else {
                $this->error('失败');
            }
        }
        $grouplist = $this->auth->getGroups($row->uid);
        $groupids = [];
        foreach ($grouplist as $k => $v)
        {
            $groupids[] = $v['id'];
        }
        $this->view->assign("row", $row);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch('add');
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            // 避免越权删除管理员
            $childrenGroupIds = $this->childrenIds;
            $adminList = $this->model->where('uid', 'in', $ids)->where('uid', 'in', function($query) use($childrenGroupIds) {
                $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
            })->select();
            if ($adminList)
            {
                $deleteIds = [];
                foreach ($adminList as $k => $v)
                {
                    $deleteIds[] = $v->uid;
                }
                $deleteIds = array_diff($deleteIds, [$this->auth->uid]);
                if ($deleteIds)
                {
                    $this->model->where('uid','in',$deleteIds)->setField('status',-1);
                    //model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
                    $this->success('删除成功');
                }else {
                    $this->error('删除失败');
                }
            }
        }else {
            $this->error('请选择你要操作的数据');
        }

        return;
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error('禁止操作');
    }
    
    
    
    
    
    
}